package chrome.GetClass;



import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PackageClasses {


    public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException {
        String packagePath = packageName.replace('.', '/');
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        List<Class<?>> classes = new ArrayList<>();

        try {
            for (File file : getClassFiles(classLoader, packagePath)) {
                String className = packageName + '.' + getClassName(file);
                classes.add(classLoader.loadClass(className));
            }
        } catch (NullPointerException e) {
            throw new ClassNotFoundException("Package " + packageName + " does not exist");
        }

        return classes;
    }

    private static List<File> getClassFiles(ClassLoader classLoader, String packagePath) {
        List<File> classFiles = new ArrayList<>();

        try {
            String filePath = classLoader.getResource(packagePath).getPath();
            classFiles = searchClassFiles(new File(filePath));
        } catch (NullPointerException e) {
            // Package does not exist
        }

        return classFiles;
    }

    private static List<File> searchClassFiles(File directory) {
        List<File> classFiles = new ArrayList<>();

        if (directory.isDirectory()) {
            for (File file : directory.listFiles()) {
                if (file.isDirectory()) {
                    classFiles.addAll(searchClassFiles(file));
                } else if (file.getName().endsWith(".class")) {
                    classFiles.add(file);
                }
            }
        }

        return classFiles;
    }

    private static String getClassName(File file) {
        String name = file.getName();
        return name.substring(0, name.length() - 6);
    }
}
